import { Fields, TableAction } from "@/types/public";
import { Button, Input, Popconfirm, Select, Space, Tag } from "antd";
import React from "react";
import { EditOutlined, DeleteOutlined } from "@ant-design/icons";
import { getOptionValueFromTable } from "@/common/common";
import RegisterAdd from "./registerAdd";

// 分组数据结构定义
export interface Group {
  /** 分组唯一标识 */
  groupId: number;

  /** 父分组ID */
  parentId?: number | null;

  /** 分组名称 */
  groupName: string;

  /** 分组类型 */
  groupType: 0 | 1; // 0-静态分组, 1-动态分组

  /** 动态分组规则 */
  dynamicRule?: any | null;

  /** 分组描述 */
  description?: string | null;

  /** 创建时间 */
  createdAt: string | Date;

  /** 更新时间 */
  updatedAt: string | Date;
}

export const createGroupField = async (
  tableAction: TableAction<Group> = {},
  existingGroups: Group[] = [], // 已有分组数据用于父分组选择
  extendProps?: any
): Promise<Fields[]> => {
  let deviceRegisterData = [];
  if (extendProps?.groupId) {
    deviceRegisterData = await getOptionValueFromTable(
      "device_register",
      {
        groupId: extendProps?.groupId || 0,
      },
      ["registerOffset", "registerName", "rwPermission"]
    );
  }
  // 生成父分组选项 (仅显示静态分组)
  const parentGroupOptions = existingGroups
    .filter((group) => group.groupType === 0)
    .map((group) => ({
      value: group.groupId,
      label: `${group.groupName} (ID:${group.groupId})`,
    }));

  return [
    {
      valueType: "number",
      inputType: "input",
      key: "groupId",
      title: "分组ID",
      disabled: true,
      dataIndex: "groupId",
      width: 100,
      isEdit: false,
      visible: true,
    },
    {
      valueType: "number",
      inputType: "input-number",
      title: "父分组ID",
      dataIndex: "parentId",
      key: "parentId",
      placeholder: "请选择父分组（支持三级嵌套）",
      options: [
        { value: null, label: "无父分组（顶层分组）" },
        ...parentGroupOptions,
      ],
      visible: true,
      rules: [
        {
          validator: async (_: any, value: any) => {
            if (value !== null && !Number.isInteger(value)) {
              return Promise.reject(new Error("请选择有效的父分组"));
            }
            return Promise.resolve();
          },
        },
      ],
    },
    {
      valueType: "string",
      inputType: "input",
      title: "分组名称",
      dataIndex: "groupName",
      key: "groupName",
      placeholder: "请输入分组名称（用户可见）",
      rules: [
        { required: true, message: "分组名称不能为空" },
        { max: 255, message: "名称长度不能超过255字符" },
      ],
    },
    {
      valueType: "string",
      inputType: "window",
      title: "采集寄存器",
      dataIndex: "readRegister",
      key: "readRegister",
      placeholder: "请点击选择",
      visible: false, // 动态分组才显示
      rules: [],
      multiple: true,
      defaultValue: "[]",
      options: deviceRegisterData,
      autoSize: { minRows: 4, maxRows: 8 },
      render: (value: any, row: Group, key: any) => {
        return <RegisterAdd groupId={row.groupId} keys={key} value={value} />;
      },
    },
    {
      valueType: "string",
      inputType: "window",
      title: "可写寄存器",
      dataIndex: "writeRegister",
      key: "writeRegister",
      placeholder: "请点击选择",
      visible: false, // 动态分组才显示
      rules: [],
      defaultValue: "[]",
      multiple: true,
      options: deviceRegisterData,
      autoSize: { minRows: 4, maxRows: 8 },
      render: (value: any, row: Group, key: any) => {
        return <RegisterAdd groupId={row.groupId} keys={key} value={value} />;
      },
    },
    {
      valueType: "string",
      inputType: "window",
      title: "异常寄存器",
      dataIndex: "abnormalRegister",
      key: "abnormalRegister",
      placeholder: "请点击选择",
      visible: false, // 动态分组才显示
      rules: [],
      defaultValue: "[]",
      multiple: true,
      options: deviceRegisterData,
      autoSize: { minRows: 4, maxRows: 8 },
      render: (value: any, row: Group, key: any) => {
        return <RegisterAdd groupId={row.groupId} keys={key} value={value} />;
      },
    },
    {
      valueType: "string",
      inputType: "window",
      title: "统计类寄存器",
      dataIndex: "totalRegister",
      key: "totalRegister",
      defaultValue: "[]",
      placeholder: "请点击选择",
      visible: false, // 动态分组才显示
      rules: [],
      multiple: true,
      options: deviceRegisterData,
      autoSize: { minRows: 4, maxRows: 8 },
      render: (value: any, row: Group, key: any) => {
        return <RegisterAdd groupId={row.groupId} keys={key} value={value} />;
      },
    },
    {
      valueType: "string",
      inputType: "window",
      title: "控制类寄存器",
      dataIndex: "controlRegister",
      defaultValue: "[]",

      key: "controlRegister",
      placeholder: "请点击选择",
      visible: false, // 动态分组才显示
      rules: [],
      multiple: true,
      options: deviceRegisterData,
      autoSize: { minRows: 4, maxRows: 8 },
      render: (value: any, row: Group, key: any) => {
        return <RegisterAdd groupId={row.groupId} keys={key} value={value} />;
      },
    },
    {
      valueType: "string",
      inputType: "window",
      title: "存储类寄存器",
      dataIndex: "saveDataRegister",
      defaultValue: "[]",

      key: "saveDataRegister",
      placeholder: "请点击选择",
      visible: false, // 动态分组才显示
      rules: [],
      multiple: true,
      options: deviceRegisterData,
      autoSize: { minRows: 4, maxRows: 8 },
      render: (value: any, row: Group, key: any) => {
        return <RegisterAdd groupId={row.groupId} keys={key} value={value} />;
      },
    },

    {
      valueType: "number",
      inputType: "radio",
      title: "分组类型",
      dataIndex: "groupType",
      key: "groupType",
      initialValue: 0,
      options: [
        { value: 0, label: "静态分组" },
        { value: 1, label: "动态分组" },
      ],
      rules: [{ required: true, message: "请选择分组类型" }],
    },
    {
      valueType: "string",
      inputType: "textarea",
      title: "动态分组规则",
      dataIndex: "dynamicRule",
      defaultValue: "{}",
      key: "dynamicRule",
      placeholder: '输入JSON格式的查询条件 例: {"condition":"type=1"}',
      visible: false, // 动态分组才显示
      rules: [],
      autoSize: { minRows: 4, maxRows: 8 },
    },
    {
      valueType: "string",
      inputType: "textarea",
      title: "分组描述",
      dataIndex: "description",
      key: "description",
      placeholder: "请输入分组描述信息",
      autoSize: { minRows: 2, maxRows: 4 },
      rules: [{ required: false }],
    },
    {
      valueType: "string",
      inputType: "date-picker",
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
      disabled: true,
      visible: true,
      rules: [{ required: false }],
    },
    {
      valueType: "string",
      inputType: "date-picker",
      title: "更新时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
      disabled: true,
      visible: true,
      rules: [{ required: false }],
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      width: 200,
      render: (_: any, record: Group) => (
        <Space size="middle">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => tableAction.edit?.(record)}
          >
            编辑
          </Button>

          <Popconfirm
            title="确定删除该分组？"
            description="删除分组可能影响关联数据"
            onConfirm={() => tableAction.delete?.([record.groupId])}
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];
};
